package com.imd.s9.impl;

import com.alibaba.fastjson.JSONObject;
import com.imd.s9.entity.TableInfo;
import com.imd.s9.service.RoleService;
import com.imd.s9.util.InitCriteria;
import com.imd.vo.s3.DepartmentVO;
import com.imd.vo.s3.UserVO;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RoleImpl implements RoleService {

    @Resource
    InitCriteria initCriteria;

    @Resource
    MongoTemplate mongoTemplate;

    @Override
    public List<UserVO> roleGetUser(String name,String tenantId) {
//        Query roleQuery = initCriteria.createQuery(Criteria.where("name").is(name));
        Query roleQuery = new Query();
        roleQuery.addCriteria(Criteria.where("isDelete").is(0).and("name").is(name).and("tenantId").is(tenantId));
        List<Document> roles = mongoTemplate.find(roleQuery,Document.class,"role");
        if(roles==null||roles.isEmpty()){
            return null;
        }
        ObjectId oid = new ObjectId(roles.get(0).getString("id"));
        Query userQuery = new Query();
        userQuery.addCriteria(Criteria.where("isDelete").is(0).and("role._id").is(oid).and("tenantId").is(tenantId));
        List<UserVO> users = mongoTemplate.find(userQuery,UserVO.class,"user");
        if(users==null||users.isEmpty()){
            return null;
        }
        return users;
    }

    @Override
    public UserVO getDepartmentLeader(String userId,String tenantId) {
        UserVO user = mongoTemplate.findById(new ObjectId(userId),UserVO.class,"user");
        ObjectId departmentId = new ObjectId(user.getDepartment().getId());
        DepartmentVO department = mongoTemplate.findById(departmentId,DepartmentVO.class,"department");
        user = mongoTemplate.findById(new ObjectId(department.getLeader().id),UserVO.class,"user");
        return user;
    }


}
